<template>
  <el-card class="container">
    <el-button
      type="primary"
      icon="el-icon-plus"
      :disabled="!category3Id"
      @click="showSaveAttr"
    >
      添加属性
    </el-button>

    <el-table v-loading="loading" :data="attrList" border class="table">
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="attrName" label="属性名" />
      <el-table-column label="属性值列表">
        <template v-slot="{ row }">
          <el-tag
            v-for="attrValue in row.attrValueList"
            :key="attrValue.id"
            class="attr-tag"
          >
            {{ attrValue.valueName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <!-- 当里面写了内容，prop就没有意义了（不会生效） -->
        <template v-slot="{ row }">
          <el-tooltip effect="dark" content="修改属性" placement="top">
            <el-button
              type="warning"
              icon="el-icon-edit"
              size="mini"
              @click="showUpdateAttr(row)"
            />
          </el-tooltip>
          <el-tooltip effect="dark" content="删除属性" placement="top">
            <el-button type="danger" icon="el-icon-delete" size="mini" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'
import { reqGetAttrList } from '@/api/product/attr'

export default {
  name: 'AttrList',
  data() {
    return {
      loading: false,
      attrList: []
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  },
  watch: {
    category3Id: {
      async handler(category3Id) {
        if (!category3Id) {
          this.attrList = []
          return
        }
        // 发送请求，请求attrList
        const { category1Id, category2Id } = this
        this.loading = true
        const { data } = await reqGetAttrList({
          category1Id,
          category2Id,
          category3Id
        })
        this.loading = false
        this.attrList = data
      },
      immediate: true
    }
  },
  methods: {
    showUpdateAttr(row) {
      // 给SaveAttr组件传递参数
      this.$emit('setAttr', row)
      // 为了显示SaveAttr组件
      this.$emit('setIsShowAttrList', false)
    },
    showSaveAttr() {
      this.$emit('setAttr', {
        attrName: '',
        attrValueList: []
      })
      this.$emit('setIsShowAttrList', false)
    }
  }
}
</script>

<style lang="sass" scoped>
.table
  margin-top: 10px
.attr-tag
  margin-right: 10px
</style>
